<!--公告管理页-->
<template>
  <div style="height: 6vh;padding:10px 20px;  background-color: #fff;">
    <span style="line-height: 60px;font-size: 20px;">通知列表</span>
    <el-button type="primary" style="float: right;margin-top: 10px;" @click="dialogVisible=true">新建公告</el-button>
  </div>

  <!-- 公告搜索卡片 -->
  <el-card style="background-color: #fff;margin:10px 10px;">
    <el-form :inline="true">
      <el-form-item label="公告标题">
        <el-input v-model="searchNoticeForm.title" placeholder="请输入公告标题" style="width: 160px;"
                  @keydown.enter="loadNotice"></el-input>
      </el-form-item>

      <el-form-item label="公告类型">
        <el-select v-model="searchNoticeForm.type" placeholder="请选择公告类型" style="width: 150px;"
                   @keydown.enter="loadNotice">
          <el-option label="次要" value="0"></el-option>
          <el-option label="一般" value="1"></el-option>
          <el-option label="重要" value="2"></el-option>
          <el-option label="紧急" value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="请选择日期">
        <el-date-picker v-model="searchNoticeForm.date" type="datetime" placeholder="请选择日期"
                        @keydown.enter="loadNotice"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button style="background-color: #00AEEc;color: #fff;" @click="loadNotice">
          <el-icon>
            <Search/>
          </el-icon>
          <span style="padding-left: 5px;">搜索</span>
        </el-button>
        <el-button style="background-color: #f0c24c;color: #fff;" @click="resetSearch">
          <el-icon>
            <RefreshRight/>
          </el-icon>
          <span style="padding-left: 5px;">重置</span>
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!--公告列表表格  -->
  <el-card style="margin: 10px;">
    <el-table :data="noticeArr" stripe  v-loading="loading" @sort-change="onSortChange">
      <el-table-column type="selection" width="45" align="center"></el-table-column>
      <el-table-column type="index" label="ID" align="center" width="80px"></el-table-column>
      <el-table-column label="标题" prop="title" align="center" width="300px" show-overflow-tooltip>
        <template #default="scope">
          <el-button link type="primary" size="small" @click="showNoticeInfo(scope.row.id)">八百标兵奔北坡{{scope.row.id}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="类型" prop="type" align="center" sortable="custom"
                       :sort-orders="['ascending','descending']">
<!--        <template v-slot:item.name="{item}">-->
        <template #default="scope">
<!--          {{ item.name }}-->
              {{ getTypeName(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" align="center"></el-table-column>
      <el-table-column label="发布者" prop="createPeople" align="center"></el-table-column>
      <el-table-column label="创建时间" prop="createTime" sortable align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" @click="edit(scope.row.id)">编辑</el-button>
          <el-button type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!--新建公告弹窗  -->
  <el-dialog :title="dialogTitle" style="width: 600px;height: 300px;" v-model="dialogVisible"
             :before-close="handleClose">
    <div style="margin: 20px 150px;">
      <el-form label-width="80px;">
        <el-row :gutter="10">
          <el-form-item label="发 布 者 : ">
            <el-input readonly :value="user.username"/>
          </el-form-item>
        </el-row>
        <el-row :gutter="10">
          <el-form-item label="创建时间：">
            <!--     默认选择当前时间     -->
            <el-date-picker
                v-model="createTime"
                type="datetime"
                placeholder="请选择日期">
            </el-date-picker>
          </el-form-item>
        </el-row>
        <el-row :gutter="10">
          <el-form-item label="创建标题：">
            <el-input placeholder="请输入公告的标题" v-model="saveNoticeForm.title"/>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <el-button type="primary" @click="addNotice">确定</el-button>
      <el-button @click="handleClose">取消</el-button>
    </template>

  </el-dialog>
</template>
<script setup>
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import router from "@/router";
import qs from "qs";
//保存当前登录人的信息，用于发布公告时的身份展示
const user = ref(getUser());

//定义变量，保存搜索栏的信息
const searchNoticeForm = ref({
  title: '',
  type: '',
  date: ''
})
//公告数据列表
const noticeArr = ref([]);
const dialogTitle = ref('新建公告');
const dialogVisible = ref(false);
onMounted(() => {
  loadNotice();
});

//保存新增弹窗中的数据
const saveNoticeForm = ref({
  createPeople: user.value.name,
  // createTime: '',
  title: ''
});
//新建公告的发布时间
const createTime = ref([]);
const handleClose = () => {
  if (confirm('您确认要关闭本弹窗吗？')) {
    dialogVisible.value = false;
    //仅清空标题，保留创建人身份
    saveNoticeForm.value = {createPeople: user.value.name, title: '', createTime: ''}
  }
};


//搜索栏加载公告的方法
const loadNotice = () => {
  loading.value = true;
  console.log(searchNoticeForm.value);
  let data = qs.stringify(searchNoticeForm.value);
  noticeArr.value = [
    {
      index: '1',
      title: 'JetBrains全新UI正式官宣标配！',
      type: '一般',
      status: '已发布',
      createPeople: 'Lisa',
      createTime: '2024-07-20'
    },
    {
      index: '2',
      title: '华为余承东回应「25 亿元转让问让问界」；鸿蒙 PC 版现身华为开发者官网；Linux Kernel 6.10释出 | 极客头条',
      type: '紧急',
      status: '已发布',
      createPeople: '李华',
      createTime: '2024-07-19'
    },
    {
      index: '3',
      title: '“AGI只需3年时间就能实现！” DeepMind 大神离职创业，最新万字访谈透露真相...',
      type: '重要',
      status: '已发布',
      createPeople: '李华',
      createTime: '2024-07-19'
    },
  ];
  loading.value = false;
};

//展示公告详情
//点击不同的公告标题，展示该公告下的具体内容，携带当前公告的id跳转至公告详情页即可
const showNoticeInfo=(id)=>{
  router.push('/noticeInfo?id='+id);
};

//实现表格中公告的类型的自定义排序
const typeData = ref([
  {code: 'less', name: '次要', level: 1},
  {code: 'normal', name: '一般', level: 2},
  {code: 'important', name: '重要', level: 3},
  {code: 'urgent', name: '紧急', level: 4}
]);
//创建一个映射，将类型代码映射到等级
const typeLevelMap = ref(new Map());
typeData.value.forEach(type => {
  typeLevelMap.value.set(type.code, type.level);
});
//获取类型名称的辅助函数
const getTypeName = (typeCode) => {
  return typeData.value.find(type => type.code === typeCode)?.name || typeCode;
};
//加载动画(true:加载）
const loading = ref(false);
const onSortChange = ({column, prop, order}) => {
  console.log('column=' + column);
  console.log('prop=' + prop);  // prop=type
  console.log('order=' + order);  // order=ascending
  if (prop === 'type') {
    loading.value = true;
    noticeArr.value.sort((a, b) => {
      // /** @type{{type:string}} */
      const aLevel = typeLevelMap.value.get(a.type) || 0;
      const bLevel = typeLevelMap.value.get(b.type) || 0;
      let modifier = order === 'descending' ? -1 : 1;
      return (aLevel - bLevel) * modifier;
    });
    setTimeout(() => {
      loading.value = false;
    }, 200);
  }
  loadNotice();
};


//重置搜索栏
const resetSearch = () => {
  searchNoticeForm.value = {};
  loadNotice();
};

//保存 新建公告弹窗 提交的内容
const addNotice = () => {
  if (!saveNoticeForm.value.title || saveNoticeForm.value.title.trim() == '') {
    ElMessage.warning('请先输入要发布的公告标题！');
    return;
  }
  console.log(saveNoticeForm.value);
  //跳转到新增公告页面：编辑公告内容
  router.push('/editNotice');
};


//编辑公告
const edit = (id) => {
  dialogVisible.value = true;
  dialogTitle.value = '编辑公告';
  console.log(id);
  if (confirm('您确认要重新编辑当前公告吗？')) {
    router.push('/editNotice'); //跳转到编辑公告页面，可对标题、内容进行再次编辑，post
  }
  //回显数据  通过id,Get得到当前公告的数据,将得到的数据传到编辑页面，并渲染到组件

};

</script>

<style scoped>

</style>